package org.example.freeswitchdemo.config;
import org.freeswitch.esl.client.inbound.Client;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class FreeswitchConfig {

    @Value("${freeswitch.host}")
    private String host;

    @Value("${freeswitch.port}")
    private int port;

    @Value("${freeswitch.password}")
    private String password;

    @Bean
    public Client eslClient() throws Exception {
        Client client = new Client();
        client.connect(host, port, password, 10);
        System.out.println("✅FreeSWITCH ESL connected to " + host + ":" + port);
        return client;
    }

    /**
     * 尝试连接 FreeSWITCH（失败会等待并重试）
     */
    private void connectWithRetry(Client client) {
        new Thread(() -> {
            while (true) {
                try {
                    if (!client.canSend()) {
                        System.out.println("🔌 尝试连接 FreeSWITCH...");
                        client.connect(host, port, password, 10);
                        System.out.println("✅ FreeSWITCH ESL 连接成功: " + host + ":" + port);
                    }
                    Thread.sleep(5000); // 每 5 秒检查一次
                } catch (Exception e) {
                    System.err.println("❌ 连接 FreeSWITCH 失败: " + e.getMessage());
                    try {
                        Thread.sleep(5000); // 失败后 5 秒再试
                    } catch (InterruptedException ignored) {
                    }
                }
            }
        }, "freeswitch-connector").start();
    }
}

